//
//  LuckyMembersVC.m
//  SMTools
//
//  Created by fengsh on 2018/12/27.
//  Copyright © 2018年 fengsh. All rights reserved.
//

#import "LuckyMembersVC.h"
#import "LuckyApi.h"
#import "LuckyUtils.h"
#import <SDWebImage/SDWebImageManager.h>
#import "LuckyEmployees.h"
#import <MagicalRecord/MagicalRecord.h>

@interface LuckyMembersVC ()
@property (weak) IBOutlet NSTableView *tabmembers;
@property (nonatomic, strong) NSMutableArray                    *dataset;
@property (nonatomic, assign) NSInteger                         currentPageIdx;
@property (nonatomic, strong) dispatch_queue_t                  queue;
@end

@implementation LuckyMembersVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
//    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
//        [LuckyEmployees MR_truncateAllInContext:localContext];
//    }];
    
    self.queue = dispatch_queue_create("com.fsh.lucky", 0);
    // Do view setup here.
//    self.tabmembers.gridStyleMask = NSTableViewSolidHorizontalGridLineMask;
    self.dataset = [NSMutableArray array];
    [self refreshData];
}

- (void)refreshData
{
    NSDictionary *p = @{@"pageNo":@(self.currentPageIdx),
                        @"pageSize":@(200),
                        @"prized":@(-1)
                        };
    [[LuckyApi api]lucky_api_post_memberlist:p comletion:^(id respobj, NSError *error) {
        if (!error) {
            NSString *retcode = respobj[@"retcode"];
            if ([retcode isEqualToString:@"00000"]) {
                NSArray *list = respobj[@"data"];
                
                dispatch_async(self.queue, ^{

                    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
                        [LuckyEmployees MR_truncateAllInContext:localContext];
                        for (NSDictionary *item in list) {
                            int64_t eid = [item[@"id"]longLongValue];
                            NSPredicate *pre =[NSPredicate predicateWithFormat:@"id = %ld",eid];
                            LuckyEmployees *employee = [LuckyEmployees MR_findFirstWithPredicate:pre inContext:localContext];
                            if (!employee) {
                                employee = [LuckyEmployees MR_createEntityInContext:localContext];
                                employee.id = [item[@"id"]longLongValue];
                            }
                            employee.name = [LuckyUtils lucky_dictionaryvalue:item[@"name"]];
                            employee.employee_no = [LuckyUtils lucky_dictionaryvalue:item[@"employeeNo"]];
                            employee.phone = [LuckyUtils lucky_dictionaryvalue:item[@"phone"]];
                            employee.photo = [LuckyUtils lucky_dictionaryvalue:item[@"photo"]];
                            employee.nike_name = [LuckyUtils lucky_dictionaryvalue:item[@"nikeName"]];
                            employee.email = [LuckyUtils lucky_dictionaryvalue:item[@"email"]];
                        }
                    } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.dataset removeAllObjects];
                            NSArray *arr = [LuckyEmployees MR_findAll];
                            if (arr) {
                                [self.dataset addObjectsFromArray:arr];
                            }
                            [self.tabmembers reloadData];
                        });
                    }];
                });
            } else {
                NSString *msg = respobj[@"msg"];
                [LuckyUtils lucky_show:msg];
            }
        } else {
            [LuckyUtils lucky_show:error.localizedDescription];
        }
    }];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return self.dataset.count;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    return 50;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSUserInterfaceItemIdentifier idf = tableColumn.identifier;
    NSTableCellView *cv = [tableView makeViewWithIdentifier:idf owner:nil];
    NSInteger colidx = [tableView columnWithIdentifier:idf];
    LuckyEmployees *obj = self.dataset[row];
    if (colidx == 0) {
        NSString *photo = obj.photo;
        if (photo.length > 0) {
            NSURL *av = [NSURL URLWithString:photo];
            [[SDWebImageManager sharedManager]loadImageWithURL:av options:SDWebImageRetryFailed progress:nil completed:^(NSImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                NSImageView *imgv = cv.subviews[0];
                imgv.image = image;
            }];
        }
    } else {
        switch (colidx) {
            case 1:
            {
                NSString *mb = obj.employee_no;
                [cv.textField setStringValue:mb?:@""];
                tableColumn.hidden = YES;
            }
                break;
            case 2:
            {
                NSString *mb = obj.name;
                [cv.textField setStringValue:mb?:@""];
            }
                break;
            case 3:
            {
                NSString *mb = obj.phone;
                [cv.textField setStringValue:mb?:@""];
            }
                break;
            case 4:
            {
                NSString *mb = obj.nike_name;
                [cv.textField setStringValue:mb?:@""];
            }
                break;
            case 5:
            {
                NSString *mb = obj.email;
                [cv.textField setStringValue:mb?:@""];
            }
                break;
            case 6:
            {
              
            }
                break;
            default:
                break;
        }
        
    }
    
    return cv;
}

- (void)tableView:(NSTableView *)tableView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
{
    if (row % 2 != 0) {
        rowView.backgroundColor = [NSColor windowBackgroundColor];
    }
}

- (IBAction)onRefreshClicked:(id)sender {
    [self refreshData];
}

@end
